#! /usr/bin/env ruby
#

class ISBN
    def initialize(base)
        @base  = base
        @count = 0
    end

    def to_s
        x=self.isbn9
        y=self.isbn13
        x9  = x[0..0]+'-'+x[1..6]+'-'+x[7..8]+'-'+x[9..9] 
        y13 = y[0..2]+'-'+y[3..3]+'-'+y[4..9]+'-'+y[10..11]+'-'+y[12..12]
        "#{x9} #{y13}"
    end    

    def incr
        @count +=1
        return self
    end

    def isbn9
        s = @base.to_s + sprintf("%02d", @count)
        sum = 0
        1.upto(9) { |i|
            sum += i * s[i-1..i-1].to_i
        }
        check = sum % 11
        return s + (check == 10 ? 'X' : check.to_s)
    end

    def isbn13
        s = "978" + @base.to_s + sprintf("%02d",@count)
        odd  = 0
        0.step(10,2) { |i|
            odd += s[i..i].to_i
        }
        even = 0
        1.step(11,2) { |i|
            even += 3 * s[i..i].to_i
        }
        check = (even + odd) % 10 
        if check > 0 then check = 10 - check end
        return s + check.to_s
    end     
end

x=ISBN.new('3939897')
100.times {
    puts x
    x.incr
}
